import React, { createContext, useContext, useReducer, useEffect, ReactNode } from 'react';
import { message } from 'antd';
import { User, UserSettings, ThemeConfig, AppError } from '../types';
import { authService } from '../services/auth';

// 应用状态接口
export interface AppState {
  // 用户认证状态
  isAuthenticated: boolean;
  user: User | null;
  
  // 应用状态
  loading: boolean;
  error: AppError | null;
  
  // UI状态
  sidebarCollapsed: boolean;
  
  // 用户设置
  settings: UserSettings;
  
  // 主题配置
  theme: ThemeConfig;
}

// 动作类型
export type AppAction =
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'SET_ERROR'; payload: AppError | null }
  | { type: 'SET_USER'; payload: User | null }
  | { type: 'SET_AUTHENTICATED'; payload: boolean }
  | { type: 'TOGGLE_SIDEBAR' }
  | { type: 'SET_SIDEBAR_COLLAPSED'; payload: boolean }
  | { type: 'UPDATE_SETTINGS'; payload: Partial<UserSettings> }
  | { type: 'UPDATE_THEME'; payload: Partial<ThemeConfig> }
  | { type: 'RESET_STATE' };

// 初始状态
const initialState: AppState = {
  isAuthenticated: false,
  user: null,
  loading: false,
  error: null,
  sidebarCollapsed: false,
  settings: {
    theme: 'light',
    language: 'zh-CN',
    sidebarCollapsed: false,
    autoRefresh: true,
    refreshInterval: 30000, // 30秒
  },
  theme: {
    primaryColor: '#1890ff',
    borderRadius: 6,
    wireframe: false,
  },
};

// Reducer函数
const appReducer = (state: AppState, action: AppAction): AppState => {
  switch (action.type) {
    case 'SET_LOADING':
      return {
        ...state,
        loading: action.payload,
      };

    case 'SET_ERROR':
      return {
        ...state,
        error: action.payload,
        loading: false,
      };

    case 'SET_USER':
      return {
        ...state,
        user: action.payload,
      };

    case 'SET_AUTHENTICATED':
      return {
        ...state,
        isAuthenticated: action.payload,
        user: action.payload ? state.user : null,
      };

    case 'TOGGLE_SIDEBAR':
      return {
        ...state,
        sidebarCollapsed: !state.sidebarCollapsed,
      };

    case 'SET_SIDEBAR_COLLAPSED':
      return {
        ...state,
        sidebarCollapsed: action.payload,
      };

    case 'UPDATE_SETTINGS':
      const newSettings = { ...state.settings, ...action.payload };
      // 保存到localStorage
      localStorage.setItem('user_settings', JSON.stringify(newSettings));
      return {
        ...state,
        settings: newSettings,
      };

    case 'UPDATE_THEME':
      const newTheme = { ...state.theme, ...action.payload };
      // 保存到localStorage
      localStorage.setItem('theme_config', JSON.stringify(newTheme));
      return {
        ...state,
        theme: newTheme,
      };

    case 'RESET_STATE':
      return {
        ...initialState,
      };

    default:
      return state;
  }
};

// Context接口
interface AppContextType {
  state: AppState;
  dispatch: React.Dispatch<AppAction>;
  
  // 便捷方法
  setLoading: (loading: boolean) => void;
  setError: (error: AppError | null) => void;
  login: (user: User) => void;
  logout: () => void;
  toggleSidebar: () => void;
  updateSettings: (settings: Partial<UserSettings>) => void;
  updateTheme: (theme: Partial<ThemeConfig>) => void;
  showError: (message: string, description?: string) => void;
  showSuccess: (message: string, description?: string) => void;
  showWarning: (message: string, description?: string) => void;
}

// 创建Context
const AppContext = createContext<AppContextType | undefined>(undefined);

// Provider组件属性
interface AppProviderProps {
  children: ReactNode;
}

// Provider组件
export const AppProvider: React.FC<AppProviderProps> = ({ children }) => {
  const [state, dispatch] = useReducer(appReducer, initialState);

  // 初始化应用状态
  useEffect(() => {
    initializeApp();
  }, []);

  // 初始化应用
  const initializeApp = async () => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });

      // 从localStorage恢复设置
      const savedSettings = localStorage.getItem('user_settings');
      if (savedSettings) {
        try {
          const settings = JSON.parse(savedSettings);
          dispatch({ type: 'UPDATE_SETTINGS', payload: settings });
        } catch (error) {
          console.error('Failed to parse saved settings:', error);
        }
      }

      // 从localStorage恢复主题
      const savedTheme = localStorage.getItem('theme_config');
      if (savedTheme) {
        try {
          const theme = JSON.parse(savedTheme);
          dispatch({ type: 'UPDATE_THEME', payload: theme });
        } catch (error) {
          console.error('Failed to parse saved theme:', error);
        }
      }

      // 检查认证状态
      if (authService.isAuthenticated()) {
        const user = authService.getUserInfo();
        if (user) {
          dispatch({ type: 'SET_USER', payload: user });
          dispatch({ type: 'SET_AUTHENTICATED', payload: true });

          // 尝试获取最新的用户信息
          try {
            const profileResponse = await authService.getProfile();
            if (profileResponse.data) {
              dispatch({ type: 'SET_USER', payload: profileResponse.data });
              authService.setUserInfo(profileResponse.data);
            }
          } catch (error) {
            console.error('Failed to fetch user profile:', error);
          }
        }
      }

      // 启动自动刷新令牌
      authService.startTokenRefresh();

    } catch (error) {
      console.error('Failed to initialize app:', error);
      dispatch({ type: 'SET_ERROR', payload: {
        code: 'INIT_ERROR',
        message: '应用初始化失败',
        details: error,
      }});
    } finally {
      dispatch({ type: 'SET_LOADING', payload: false });
    }
  };

  // 便捷方法
  const contextValue: AppContextType = {
    state,
    dispatch,

    setLoading: (loading: boolean) => {
      dispatch({ type: 'SET_LOADING', payload: loading });
    },

    setError: (error: AppError | null) => {
      dispatch({ type: 'SET_ERROR', payload: error });
    },

    login: (user: User) => {
      dispatch({ type: 'SET_USER', payload: user });
      dispatch({ type: 'SET_AUTHENTICATED', payload: true });
    },

    logout: async () => {
      try {
        await authService.logout();
      } catch (error) {
        console.error('Logout failed:', error);
      } finally {
        dispatch({ type: 'RESET_STATE' });
      }
    },

    toggleSidebar: () => {
      dispatch({ type: 'TOGGLE_SIDEBAR' });
    },

    updateSettings: (settings: Partial<UserSettings>) => {
      dispatch({ type: 'UPDATE_SETTINGS', payload: settings });
    },

    updateTheme: (theme: Partial<ThemeConfig>) => {
      dispatch({ type: 'UPDATE_THEME', payload: theme });
    },

    showError: (msg: string, description?: string) => {
      if (description) {
        message.error(`${msg}: ${description}`);
      } else {
        message.error(msg);
      }
    },

    showSuccess: (msg: string, description?: string) => {
      if (description) {
        message.success(`${msg}: ${description}`);
      } else {
        message.success(msg);
      }
    },

    showWarning: (msg: string, description?: string) => {
      if (description) {
        message.warning(`${msg}: ${description}`);
      } else {
        message.warning(msg);
      }
    },
  };

  return (
    <AppContext.Provider value={contextValue}>
      {children}
    </AppContext.Provider>
  );
};

// Hook使用Context
export const useAppContext = (): AppContextType => {
  const context = useContext(AppContext);
  if (context === undefined) {
    throw new Error('useAppContext must be used within an AppProvider');
  }
  return context;
};

// 认证Hook
export const useAuth = () => {
  const { state, login, logout } = useAppContext();
  return {
    isAuthenticated: state.isAuthenticated,
    user: state.user,
    isAdmin: state.user?.role === 'admin',
    login,
    logout,
  };
};

// 主题Hook
export const useTheme = () => {
  const { state, updateTheme } = useAppContext();
  return {
    theme: state.theme,
    updateTheme,
  };
};

// 设置Hook
export const useSettings = () => {
  const { state, updateSettings } = useAppContext();
  return {
    settings: state.settings,
    updateSettings,
  };
};

export default AppContext;
